package com.mouchel.gwt.xpath.client.impl;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.Window;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.Node;
import com.google.gwt.xml.client.impl.XPathUtil;

import java.util.ArrayList;
import java.util.List;

public abstract class XPathImpl
{
	private static XPathImpl impl = GWT.create(XPathImpl.class);
	
	public static XPathImpl getInstance()
	{
		return impl;
	}
	
	/**
	 * 
	 * @param element
	 * @param xpath
	 */
	public List<Node> evaluate(Element element, String xpath)
	{
		List<JavaScriptObject> results = new ArrayList<JavaScriptObject>();
		evaluateImpl(element, xpath, results);
		
		List<Node> nodes = new ArrayList<Node>();
		for (JavaScriptObject o : results)
		{
			nodes.add(XPathUtil.build(o));
		}
	
		return nodes;
	}
	
	/**
	 * Browser specific method for performing the xpath
	 * 
	 * Still new to this jsni stuff, so rather than figure out how to return
	 * an array from the native methods, I'm just going to pass a list in
	 * 
	 * @param element The element to start the xpath query at
	 * @param xpath The xpath query to evaluate
	 * @param results A list to put the results in
	 */
	protected abstract void evaluateImpl(Element element, String xpath, List<JavaScriptObject> results);
}